package com.ringtheweb.persistence.dao.jpa;

import java.util.List;

import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ringtheweb.model.User;
import com.ringtheweb.persistence.dao.IUserDAO;

/**
 * JPA implementation of {@link IUserDAO}
 * @author ldewavri
 *
 */
@Repository("userDAO")
public class UserDAO extends GenericJPADAO<User, Long> 
		implements IUserDAO{

	/**
	 * {@inheritDoc}
	 */
	@Override
	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	public User findByLogin(String login) {
		
		List<User> users = getEntityManager().createNamedQuery("findByLogin").
			setParameter("loginName", login).getResultList();
		if (users.size() > 1 ) {
			//TODO : log
			return null;
		}
		if (users.size()==0) {
			// TODO : log
			return null;
		}
		return users.get(0);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	public User findByLoginAndPassword(String login, String clearTextPassword) {
		
		// Create a temporary user
		User tempUser = new User(login);
		tempUser.setPassword(clearTextPassword);
		User dbUser = null;
		try {
			dbUser = (User)getEntityManager().createNamedQuery("findByLoginAndPassword").
			setParameter("loginName", tempUser.getLoginName()).setParameter("password", tempUser.getPassword())
			.getSingleResult();
		}
		catch(NoResultException e) {
		}
		catch (NonUniqueResultException e){
		}
		return dbUser;
	}
	
	
	/* (non-Javadoc)
	 * @see com.ringtheweb.persistence.dao.IUserDAO#findByRole(com.ringtheweb.model.Role)
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	public List<User> findByRoleName(String roleName) {
		Criteria criteria = getCurrentSession().createCriteria(User.class);
		criteria.createAlias("roles", "r");
		criteria.add(Restrictions.in("r.name", new String[]{roleName}));
		return criteria.list();
	}

}
